package base.utils;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import jxl.Image;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;

public class ExcelFile {
	@SuppressWarnings("resource")
	public static List<Map> readExcel(InputStream is,String savePath) {//使用的方法
		FileOutputStream os = null;
		List<Map> list = new ArrayList<Map>();
		List<String> listImg;
		File dirFile = new File(savePath);
		if (!dirFile.exists()) {
			System.out.println(savePath + "wenjj");
			dirFile.mkdirs();
		}
		Map map = null;
		try {
			// 创建输入流，读取Excel
//			InputStream is = new FileInputStream(file.getAbsolutePath());
			// jxl提供的Workbook类
			Workbook wb = Workbook.getWorkbook(is);
			// Excel的页签数量
			int sheet_size = wb.getNumberOfSheets();
			
			for (int index = 0; index < sheet_size; index++) {
				// 每个页签创建一个Sheet对象
				Sheet sheet = wb.getSheet(index);
	
 //对图片的处理
 			int imgNumber = sheet.getNumberOfImages();// 获得sheet所包含的图片数
				System.out.println("zxzximgNumber=="+imgNumber);
				listImg = new ArrayList<String>();
				 for (int i = 0; i < imgNumber; i++) {
	                    Image image = sheet.getDrawing(i);
	                    byte[] imageData = image.getImageData();
	                    String time = new  SimpleDateFormat("yyyyMMddHHmmssS").format(new Date());
	                    String fileName = time
	                            + ".jpg";
	                    File file = new File(savePath+ fileName);
	                    System.out.println(file.getPath());
	                    os = new FileOutputStream(file);// 建立一个上传文件的输出流
	                    os.write(imageData, 0, imageData.length);// 将文件写入服务器
	                    listImg.add(i, file.getName());
	                    System.out.println("zxzxzx!!!!!!"+file.getName());
	                }
				// sheet.getRows()返回该页的总行数
				for (int i = 0; i < sheet.getRows(); i++) {
					// sheet.getColumns()返回该页的总列数
					map = new HashMap<String, String>();
					int j = 0;
					for (; j < sheet.getColumns(); j++) {
						
						String cellinfo = sheet.getCell(j, i).getContents();
						if(cellinfo!=null){
							map.put(j+"", cellinfo);
						}else {
							map.put(j+"", "");
						}
						
//						System.out.println(cellinfo);
					}
					if(i==0){
						
					}else if(i<=(listImg.size())){
						map.put(j+"", listImg.get(i-1));
						System.out.println("zxzxzx!!!!!!"+listImg.get(i-1));
					}else{
						map.put(j+"", "1");
					}
					list.add(map);
				}
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (BiffException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return list;
	}
	
}
